<template>
  <header class="header">
    <section class="todoapp">
      <!-- 4--调用组件 -->
      <TodoHeader @create="createFn" :arr="list"></TodoHeader>
      <TodoMain :arr="list" :isSel="isSel" @removeFn="destroyFn"></TodoMain>
      <TodoFooter
        :arr="list"
        @changeevent="chengeFn"
        @clear="clearFn"
      ></TodoFooter>
    </section>
  </header>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";
// 2.0 引入组件
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
  // 3.0  注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  // 数据
  data() {
    return {
      list: JSON.parse(localStorage.getItem("plist")) || [],
      isSel: "all",
    };
  },
  // 方法
  methods: {
    // 子组件 的处理函数
    createFn(val) {
      // 处理id小于0的情况
      let id =
        this.list.length > 0 ? this.list[this.list.length - 1].id + 1 : 100;
      // 增加到list里
      this.list.push({
        id: id,
        name: val,
        isDone: false,
      });
    },
    // 删除任务
    destroyFn(id) {
      // 找到id
      let index = this.list.findIndex((obj) => {
        obj.id == id;
      });
      // splice删除数据
      this.list.splice(index, 1);
    },
    // 接收todoFOOTer子件传过来的值
    chengeFn(isSel) {
      console.log(isSel);
      this.isSel = isSel;
    },
    // 清除已完成的任务 筛选不会改变原数组 要重新赋值
    clearFn() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("plist", JSON.stringify(this.list));
      },
    },
  },
};
</script>